from fastapi import FastAPI, File, Response
from docxcompose.composer import Composer
from docx import Document
import io

app = FastAPI()

@app.post("/doc")
async def doc(file: bytes = File(...)):
    with io.BytesIO(file) as f:
        primary = Document('./模版.docx')

        first_paragraph = primary.paragraphs[0]
        if not first_paragraph.text.strip():
            primary.paragraphs[0]._element.getparent().remove(primary.paragraphs[0]._element)

        replica = Document(f)
        composer = Composer(primary)
        composer.append(replica)

        merged_file = io.BytesIO()
        composer.save(merged_file)

        merged_content = merged_file.getvalue()
        return Response(content=merged_content, media_type='application /vnd.openxmlformats-officedocument.wordprocessingml.document', headers={'Content-Disposition': f'attachment; filename="result.docx"'})